/*-------------------二分法查找数据-----------------------*/
function binarySearch(arr, search) {
	/*---------首先先给进行排序--------*/

	arr.sort((a, b) => a - b);

	let last = arr.length - 1,
		start = 0,
		middle,
		count = 0,
		index = -1;
	while (last >= start) {
		count++;
		middle = Math.floor((last + start) / 2);
		if (arr[middle] == search) {
			index = middle;
			break;
		} else if (arr[middle] < search) {
			start = middle + 1;
		} else {
			last = middle - 1;
		}
	}
	console.log("您要查找的数字在" + index);
	console.log("循环了" + count);
}

/*==========================给对象或数组去重===============================*/

function unique(arr) {
	return Array.from(new Set(arr));
}
Array.prototype.unique = function () {
	return Array.from(new Set(arr));
};

/*==========================将字符串转化为数组===============================*/

function toStringArray(str) {
	let arr = new Array();
	for (let i = 0; i < str.length; i++) {
		arr.push(str.charAt(i));
	}
	return arr;
}

String.prototype.toStringArray = function () {
	let arr = new Array();
	for (let i = 0; i < this.length; i++) {
		arr.push(this.charAt(i));
	}
	return arr;
};

/*==========================判断是否为闰年================================*/

function leapYear(year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		return true;
	} else {
		return false;
	}
}

Date.prototype.leapYear = function (year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		return true;
	} else {
		return false;
	}
};

/*==========================生成一个随机色================================*/

function randomColor() {
	// let color = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
	// let random,
	// 	str = "#";
	// for (let i = 0; i < 6; i++) {
	// 	random = Math.round(Math.random() * 15);
	// 	str += color[random];
	// }
	return '#'+Math.random().toString(16).substring(2,8);
}

/*==========================随机生成数================================*/

function getRandom(max, min) {
	return Math.floor(Math.random() * (max - min) - min);
}

/*==========================随机生成不重复的数================================*/

function randomTime(arr, time) {
	let newArr = [],
		condition;
	for (let i = 0; i < time; i++) {
		do {
			random = Math.floor(Math.random() * arr.length);
			if (newArr.indexOf(arr[random]) == -1) {
				newArr.push(arr[random]);
				condition = false;
			} else {
				condition = true;
			}
		} while (condition);
	}
	return newArr;
}

/*==========================绑定对象================================*/

function $(value) {
	if (document.querySelectorAll(value).length == 1) {
		return document.querySelector(value);
	} else if (document.querySelectorAll(value).length > 1) {
		return document.querySelectorAll(value);
	} else {
		return "未找到这个对象";
	}
}

/*==========================拖动================================*/

function dragMove(obj) {
	obj.addEventListener("mousedown", function (e) {
		let x = e.pageX - this.offsetLeft;
		let y = e.pageY - this.offsetTop;

		document.addEventListener("mousemove", move);

		function move(e) {
			let resultX = e.pageX - x;
			let resultY = e.pageY - y;
			obj.style.left = resultX + "px";
			obj.style.top = resultY + "px";
		}

		document.addEventListener("mouseup", function (e) {
			document.removeEventListener("mousemove", move);
		});

		e.stopPropagation();
	});
}

/*==========================动画函数（水平移动）================================*/
function animateHorizontal(obj, target, callback) {
	obj.timer = setInterval(() => {
		if (obj.offsetLeft == target) {
			clearInterval(obj.timer);
			callback && callback();
		}
		let begin = (target - obj.offsetLeft) / 10;
		begin = begin > 0 ? Math.ceil(begin) : Math.floor(begin);
		begin = obj.offsetLeft + begin;

		obj.style.left = begin + "px";
	}, 10);
}

/*==========================匀速动画函数（完整版）================================*/

function move(obj, speed, target, attr, callback) {
	let oldSpeed = 0;
	clearInterval(obj.timer);
	if (target < parseInt(getComputedStyle(obj, null)[attr])) {
		speed = -speed;
	}
	obj.timer = setInterval(() => {
		oldSpeed = parseFloat(getComputedStyle(obj, null)[attr]) + speed;
		if ((oldSpeed > target && speed > 0) || (oldSpeed < target && speed < 0)) {
			oldSpeed = target;
		}
		if (attr === "opacity") {
			obj.style[attr] = oldSpeed;
		} else {
			obj.style[attr] = oldSpeed + "px";
		}

		if (oldSpeed == target) {
			clearInterval(obj.timer);
			if (callback) {
				callback && callback();
			}
		}
	}, 15);
}

/*==========================快到慢动画函数（完整版）================================*/

function easeMove(obj, speed, target, attr, callback) {
	let oldSpeed = 0;
	clearInterval(obj.timer);

	obj.timer = setInterval(() => {

		oldSpeed = (target - parseFloat(getComputedStyle(obj, null)[attr])) / speed
		
		oldSpeed = oldSpeed>0?Math.ceil(oldSpeed):Math.floor(oldSpeed)

		if (attr === "opacity") {
			obj.style[attr] = parseFloat(getComputedStyle(obj, null)[attr])+oldSpeed;
		} else {
			obj.style[attr] = parseFloat(getComputedStyle(obj, null)[attr])+oldSpeed + "px";
		}

		if (parseFloat(getComputedStyle(obj, null)[attr]) == target) {
			clearInterval(obj.timer);
			if (callback) {
				callback && callback();
			}
		}
	}, 15);
}

/*==========================(改进)动画函数（完整版）================================*/

function betterMove(obj, speed, json, callback) {
	clearInterval(obj.timer);

	obj.timer = setInterval(() => {
		var f = true;

		for (const item in json) {
			let oldSpeed = 0,nowPlace = 0;

			if (item === "opacity") {
				nowPlace = Math.round(parseFloat(getComputedStyle(obj, null)[item] * 100));
				
			} else {
				nowPlace = parseInt(getComputedStyle(obj, null)[item]);
			}
			oldSpeed = (json[item] - nowPlace) / speed

			oldSpeed = oldSpeed>0?Math.ceil(oldSpeed):Math.floor(oldSpeed)

			if (json[item] != nowPlace+oldSpeed) f = false;

			if (item === "opacity") {
				console.log(nowPlace);
				obj.style[item] = (nowPlace+oldSpeed)/100;
			} else {
				obj.style[item] = nowPlace+oldSpeed + "px";
			}
		}
		if (f) {
			clearInterval(obj.timer);
			if (callback) {
				callback && callback();
			}
		}
	}, 15);
}

/*==========================获取鼠标当前位置（适配老浏览器）================================*/

function getPos(e) {
	let pageX = document.documentElement.scrollLeft || document.body.scrollLeft;
	let pageY = document.documentElement.scrollTop || document.body.scrollTop;

	return { x: pageX + e.clientX, y: pageY + e.clientY };
}

/*==========================获取当前时间================================*/

function nowTime() {
	let date = new Date();
	let year = 0,
		month = 0,
		day = 0,
		hour = 0,
		min = 0,
		sec = 0;

	year = date.getFullYear();
	month = date.getMonth() + 1 < 10 ? "0" + date.getMonth() + 1 : date.getMonth() + 1;
	day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
	sec = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

	return year + ":" + month + ":" + day + " " + hour + ":" + min + ":" + sec;
}

/*==========================选项卡================================*/

function tab(control, change) {
	for (let i = 0; i < change.length; i++) {
		control[i].addEventListener("click", () => {
			for (let j = 0; j < change.length; j++) {
				change[j].style.display = "none";
			}
			change[i].style.display = "flex";
		});
	}
}

/*==========================选项卡的附带效果（小样式的变化）================================*/

function autoClass(obj, change, num) {
	for (let i = 0; i < obj.length; i++) {
		obj[i].classList.remove(change);
	}
	if (num>obj.length-1) {
	    num = 0
	}
	obj[num].classList.add(change);
}

/*==========================添加删除样式================================*/

function changeClass(obj, change) {
	for (let i = 0; i < obj.length; i++) {
		obj[i].addEventListener("click", () => {
			for (let j = 0; j < obj.length; j++) {
				obj[j].classList.remove(change);
			}
			obj[i].classList.add(change);
		});
	}
}

/*==========================轮播图(无左右箭头)================================*/

function carousel_all(point, slide, time) {
	console.log(arguments);
	let count = 0;

	for (let i = 0; i < point.length; i++) {
		point[i].addEventListener("click", () => {
			slide.style.transition = "all 1s";
			slide.style.left = -i * slide.children[0].offsetWidth + "px";
			count = i;
			autoClass(point, "point_change", count);
		});

		point[i].addEventListener("mouseover", () => {
			clearInterval(timer);
		});
		point[i].addEventListener("mouseout", () => {
			timer = setInterval(autoPlay, time);
		});
	}

	let timer = setInterval(autoPlay, time);

	slide.addEventListener("transitionend", function () {
		if (count >= slide.children.length - 1) {
			count = 0;
			slide.style.left = -0 + "px";
			slide.style.transition = "none";
		}
	});

	function autoPlay() {
		count++;
		slide.style.transition = "all 1s";
		slide.style.left = -count * slide.children[0].offsetWidth + "px";
		autoClass(point, "point_change", count);
	}
}

/*==========================轮播图(有左右箭头)================================*/

function carousel_whole(slide, point, time, left_arrow, right_arrow) {
	let count = 0,
		f = true;
	for (let i = 0; i < point.length; i++) {
		point[i].addEventListener("click", () => {
			slide.style.transition = "all 1s";
			slide.style.left = -i * slide.children[0].offsetWidth + "px";
			count = i;
			autoClass(point, "point_change", count);
		});
	}
	slide.appendChild(slide.firstElementChild.cloneNode(true));

	slide.parentNode.addEventListener("mouseover", () => {
		clearInterval(timer);
	});
	slide.parentNode.addEventListener("mouseout", () => {
		timer = setInterval(() => {
			right_arrow.click();
		}, time);
	});

	let timer = setInterval(() => {
		right_arrow.click();
		console.log(count);
	}, time);
	slide.addEventListener("transitionend", () => {
		if (count >= slide.children.length - 1) {
			count = 0;
			slide.style.left = -0 + "px";
			slide.style.transition = "none";
		} else if (count < 0) {
			count = slide.children.length - 1;
			slide.style.left = -count * slide.children[0].offsetWidth + "px";
			slide.style.transition = "none";
		}
		f = true;
	});
	left_arrow.addEventListener("click", () => {
		if (f) {
			f = false;
			count--;
			slide.style.transition = "all 1s";
			slide.style.left = -count * slide.children[0].offsetWidth + "px";
			autoClass(point, "point_change", count);
		}
	});
	right_arrow.addEventListener("click", () => {
		if (f) {
			f = false;
			count++;
			slide.style.transition = "all 1s";
			slide.style.left = -count * slide.children[0].offsetWidth + "px";
			autoClass(point, "point_change", count);
		}
	});
}

/*==========================移动端轮播图================================*/

function Carousel(el,obj){
    var self = this;
    this.el = document.querySelector(el)

    this.handle ={
        datalist: obj.datalist,
        length: obj.datalist.length,
        ul: obj.ul ? this.el.querySelector(obj.ul) : this.el.querySelector('ul'),
        ol: obj.ol ? this.el.querySelector(obj.ol) : this.el.querySelector('ol'),
        speed: obj.speed ? obj.speed : 1000,
        autoPlay: obj.autoPlay ? true : false,
        showView:1,
        startDis:0,
        endDis:0,
        moveDis:0,
        closeTime:null
    }

    this.handle.datalist.forEach((item,index) => {
        let oli = document.createElement('li')
        let uli = document.createElement('li')
        let img = document.createElement('img')
        img.src = item.smallImg;

        index===0?oli.className = 'active':''

        uli.appendChild(img);
        this.handle.ul.appendChild(uli);
        this.handle.ol.appendChild(oli);
    });
    
    this.reset()

    function run(){
        if (self.handle.autoPlay) {
            clearInterval(self.handle.closeTime)
            self.handle.closeTime = setInterval(()=>{
                self.run('a')
            },self.handle.speed)
        }
    }
    run()

    this.el.addEventListener('touchstart',(e)=>{
        clearInterval(self.handle.closeTime)
        this.handle.startDis = e.targetTouches[0].clientX;
    })

    this.el.addEventListener('touchmove',(e)=>{
        this.handle.endDis = this.handle.startDis - e.targetTouches[0].clientX;
        let a = self.width()*this.handle.showView;
        this.handle.ul.style.left = -a + -this.handle.endDis+'px'
    })

    this.el.addEventListener('touchend',(e)=>{
        this.run(this.handle.endDis)
        this.handle.endDis = 0;
        this.handle.startDis = 0;
        run()
    })

}

Carousel.prototype = {
	constructor:Carousel,
    run:function(distance){
        if (Math.abs(distance)>(this.width()/5) || isNaN(distance)) {
            if (distance>0) {
                this.handle.showView > this.handle.length+1 ? (this.handle.showView = 0) : NaN;
                this.handle.showView++;
            }else if(distance<0){
			    this.handle.showView <0 ? (this.handle.showView = this.size()) : NaN;
                this.handle.showView--;
            }else{
                this.handle.showView > this.handle.length ? (this.handle.showView = 0) : NaN;
                this.handle.showView++;
            }
        }else if(Math.abs(distance)<(this.width()/5)){

        }
        this.init()
    },
    init:function(){
        this.judge(this.handle.showView, "width", "left");
        autoClass(this.handle.ol.children, "active", this.handle.showView);
        betterMove(this.handle.ul,10,{left:-this.width()*this.handle.showView})
    },
    reset: function () {
        let first = this.handle.ul.children[0].cloneNode(true),
            last = this.handle.ul.children[this.handle.length-1].cloneNode(true);
        this.handle.ul.appendChild(first);
        this.handle.ul.insertBefore(last,this.handle.ul.firstElementChild)
        this.handle.ul.style.left = -this.width()+'px'
    },
    width:function(){
        return this.handle.ul.children[0].offsetWidth
    },
    size:function(){
        return this.handle.length
    },
    judge: function (num, attr, attr2) {
		if (num < 0) {
			this.handle.showView = this.size();
			this.handle.ul.style[attr2] = -this.getStyle(this.handle.ul.children[0], attr) * this.handle.showView + "px";
			this.handle.showView--;
		}
		if (num > this.size()) {
			this.handle.showView = 0;
			this.handle.ul.style[attr2] = -this.getStyle(this.handle.ul.children[0], attr) * this.handle.showView + "px";
			this.handle.showView++;
		}
	},
    getStyle: function (obj, attr) {
		if (obj.currentStyle) {
			return parseInt(obj.currentStyle[attr]);
		} else {
			return parseInt(getComputedStyle(obj, null)[attr]);
		}
	},
}